<template>
<div class="Add">
  <!-- 面包屑导航区域 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图区域 -->
  <el-card>
    <!-- 信息提示 -->
    <el-alert title="添加商品信息" type="warning" center show-icon :closable="false"></el-alert>
    <!-- 步骤条区域 -->
    <el-steps :space="200" :active="activeStep - 0" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 添加商品的表单 -->
    <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef" label-width="100px" label-position="top">
      <!-- 标签页 -->
      <el-tabs v-model="activeStep" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClicked">
        <el-tab-pane label="基本信息" name="0">
          <!-- 基本信息表单项 -->
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-cascader v-model="addGoodsForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <!-- 商品参数表单项 -->
          <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox border v-for="(cb, index) in item.attr_vals" :label="cb" :key="index"></el-checkbox>
            </el-checkbox-group>
            <!-- <pre>{{ item }}</pre> -->
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <!-- 商品属性表单项 -->
          <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <!-- 上传图片 -->
          <el-upload :headers="headerObj" :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :on-success="handleSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品描述" name="4">
          <!-- 商品描述富文本编辑器 -->
          <quill-editor ref="addGoodsEditorRef" v-model="addGoodsForm.goods_introduce" />
          <el-button type="primary" @click="add">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
  <!-- 图片预览对话框 -->
  <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
    <img :src="previewPath" alt="" class="previewImg" />
  </el-dialog>
</div>
</template>

<script>
import _ from "lodash";
export default {
  name: "Add",
  data() {
    return {
      // 当前活跃的步骤条，需要为字符串
      activeStep: "0",
      // 添加商品的表单
      addGoodsForm: {
        goods_name: "",
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        // 商品所属的分类数组
        goods_cat: [],
        // 商品图片
        pics: [],
        // 商品介绍
        goods_introduce: "",
        // 商品参数
        attrs: [],
      },
      // 表单验证规则
      addGoodsFormRules: {
        goods_name: [{
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        }],
        goods_price: [{
          required: true,
          message: '请输入商品价格',
          trigger: 'blur'
        }],
        goods_weight: [{
          required: true,
          message: '请输入商品重量',
          trigger: 'blur'
        }],
        goods_number: [{
          required: true,
          message: '请输入商品数量',
          trigger: 'blur'
        }],
      },
      // 分类列表
      cateList: [],
      // 级联选择器的属性
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 商品动态参数
      manyTableData: [],
      // 商品静态属性
      onlyTableData: [],
      // 上传图片的 url
      uploadURL: "http://127.0.0.1:8999/api/private/v1/upload",
      // 上传图片也需要在消息头添加 token
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片时，图片的实际路径
      previewPath: "",
      // 图片预览是否可见
      previewVisible: false,
    };
  },
  computed: {
    // 商品分类的 id
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2];
      }
      return null;
    },
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      const {
        data: res
      } = await this.$request("categories");
      if (res.meta.status !== 200)
        return thius.$message.error("服务器错误，获取商品分类数据失败");
      this.cateList = res.data;
    },
    // 监听级联选择器的变化
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = [];
      }
    },
    // 离开标签时自动触发
    beforeTabLeave(activeName, oldActiveName) {
      // 强制选择三级分类
      if (oldActiveName === "0" && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 监听标签的点击
    async tabClicked() {
      // 如果点击商品参数标签，请求商品动态参数
      if (this.activeStep === "1") {
        const {
          data: res
        } = await this.$request(
          `categories/${this.cateId}/attributes`, {
            params: {
              sel: "many",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("服务器错误，获取商品动态参数失败");
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
      }
      // 如果点击商品属性标签，请求商品静态属性
      else if (this.activeStep === "2") {
        const {
          data: res
        } = await this.$request(
          `categories/${this.cateId}/attributes`, {
            params: {
              sel: "only",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("服务器错误，获取商品静态属性失败");
        this.onlyTableData = res.data;
      }
    },
    // 点击图片进行预览
    handlePreview(file) {
      // 图片的路径
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    // 点击 × 移除图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const index = this.addGoodsForm.pics.findIndex(
        (item) => item.pic === filePath
      );
      this.addGoodsForm.pics.splice(index, 1);
    },
    // 上传成功触发，保存图片路径到表单
    handleSuccess(response) {
      const picInfo = {
        pic: response.data.tmp_path,
      };
      this.addGoodsForm.pics.push(picInfo);
    },
    // 点击确定按钮添加商品
    add() {
      this.$refs.addGoodsFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项！");
        const form = _.cloneDeep(this.addGoodsForm);
        form.goods_cat = form.goods_cat.join(",");
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addGoodsForm.attrs.push(newInfo);
        });
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addGoodsForm.attrs.push(newInfo);
        });
        form.attrs = this.addGoodsForm.attrs;
        const {
          data: res
        } = await this.$request.post('goods', form);
        if (res.meta.status !== 201) return this.$message.eror('添加商品失败');
        this.$message.success('添加商品成功');
        this.$router.push('/goods');
      });
    },
  },
};
</script>

<style lang="less" scoped>
.previewImg {
  width: 100%;
}
</style>
